//
//  OrderPayManager.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/12/14.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "OrderPayManager.h"
#import "XHPKit.h"

@interface OrderPayManager ()

@property (nonatomic, copy) void (^ resultBlock) (NSString *result, NSError *error);

@property (nonatomic, copy) NSString *orderid;


@end

@implementation OrderPayManager


+ (instancetype)sharedManager {
    
    static OrderPayManager *payManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        payManager = [[OrderPayManager alloc] init];
        
    });
    return payManager;
}

- (void)ticketModel:(UploadTicketOrderModel *)model payType:(PayType)payType orderid:(NSString *)orderid vc:(UIViewController *)vc andBlock:(void (^)(NSString *result, NSError *error))block {
    
    self.resultBlock = block;
    
    [NetAPIManager getPaymentinfoWithPaymentID:model.ticketID couponid:nil orderid:orderid ticketmodel:model ordernumber:nil payType:payType merchType:MerchTypeTicket andBlock:^(id result, NSError *error) {
        if (error) {
            if (self.resultBlock) {
                self.resultBlock(nil,error);
            }
            return;
        }
        
        NSString *orderid = result[@"orderid"];
        
        id payInfo = result[@"notorderid"];
        model.orderid = orderid;
        self.orderid = orderid;
        if ([payInfo isKindOfClass:[NSString class]] && [payInfo isEqualToString:@"free"]) {
            
            [self verifyOrderWithOrderID:orderid notorderID:@"free" payType:payType currency:nil];
            return;
        }
        
        switch (payType) {
                
            case PayTypeAlipay: {
                
                [self payAlipayWithOrderString:payInfo];
            }
                break;
                
            case PayTypeWX: {
                
                [self payWXWithOrderObj:payInfo];
            }
                break;
                
//            case PayTypePaypal: {
//                
//                [self payPayPalWithOrderObj:payInfo vc:vc];
//            }
//                break;
//                
//            case PayTypeApplepay: {
//                
//                [self payApplePayObj:payInfo vc:vc];
//            }
//                break;
                
            case PayTypeIAP: {
                
                
                [IGUtil showToast:@"你来错地方啦"];
            }
                break;
                
            default:
                break;
        }
        
    }];
    
}


- (void)ticketModel:(UploadTicketOrderModel *)model payType:(PayType)payType vc:(UIViewController *)vc andBlock:(void (^)(NSString *result, NSError *error))block {
    
    [self ticketModel:model payType:payType orderid:nil vc:vc andBlock:block];
}

- (void)reticketWithOrderID:(NSString *)ticketorderid payType:(PayType)payType vc:(UIViewController *)vc andBlock:(void (^)(NSString *result, NSError *error))block {
    
    [self ticketModel:nil payType:payType orderid:ticketorderid vc:vc andBlock:block];
}

#pragma 验证结果
- (void)verifyOrderWithOrderID:(NSString *)orderID notorderID:(NSString *)notorderID payType:(PayType)paytype currency:(NSString *)currency {
    
    if (orderID.length == 0) {
        
        if (self.resultBlock) {
            self.resultBlock(nil, [NSError errorWithDomain:[AppManager sharedManager].baseURLStr code:-1 userInfo:@{@"errmsg":@"订单丢失"}]);
        }
        return;
    }
    @weakify(self);
    [NetAPIManager verifyPaymentOrderID:orderID notorderid:notorderID currency:currency payType:paytype andBlock:^(id result, NSError *error) {
        @strongify(self);
        
        if (error) {
            
            if (self.resultBlock) {
                @weakify(self);
                [IGAlertView alertWithTitle:@"" message:[IGUtil tipFromError:error] cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_RETRY", nil) commit:^{
                    @strongify(self);
                    [self verifyOrderWithOrderID:orderID notorderID:notorderID payType:paytype currency:currency];
                    
                } cancel:^{
                    @strongify(self);
                    self.resultBlock(result,error);
                }];
            }
            
            return;
        }
        
        if (result[@"orderstatus"] && [result[@"orderstatus"] integerValue] != 1) {
            
            error = [NSError errorWithDomain:[AppManager sharedManager].baseURLStr code:PAY_FILEDCOED_SERVERERROR userInfo:@{@"errmsg":@"支付失败，详情请联系客服"}];
        }
        
        if (self.resultBlock) self.resultBlock(result,error);
    }];
}


// -----------------------------------------------------------------------------------------------------------
// -------------------------------------- 支付宝 ----------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
#pragma mark -支付宝支付 请求
- (void)payAlipayWithOrderString:(NSString *)orderString {
    
    NSString *errmsg = [[XHPKit defaultManager] alipOrder:orderString fromScheme:@"imguider" completed:^(NSDictionary *resultDict) {
        
        [self paymentResultCallback:resultDict payType:PayTypeAlipay];
    }];
    
    if (errmsg.length > 0) {
        
        NSError *payError = [NSError errorWithDomain:[AppManager sharedManager].baseURLStr code:-1 userInfo:@{@"errmsg":errmsg}];
        
        if (self.resultBlock) {
            self.resultBlock(nil, payError);
        }
    }
}

// -----------------------------------------------------------------------------------------------------------
// -------------------------------------- 微 信 -----------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------------
#pragma mark -微信支付 请求
- (void)payWXWithOrderObj:(NSDictionary *)result {
    
    UInt32 timeStamp = (UInt32)[result[@"timeStamp"] integerValue];
    
    XHPWxReq *request = [[XHPWxReq alloc] init];
    request.openID = result[@"appId"];
    request.nonceStr = result[@"nonceStr"];
    request.partnerId = result[@"partnerId"];
    request.sign = result[@"paySign"];
    request.package = result[@"pkg"];
    request.prepayId = result[@"prepayId"];
    request.timeStamp = timeStamp;
    
   
    NSString *errmsg = [[XHPKit defaultManager] wxpOrder:request completed:^(NSDictionary *resultDict) {
        
        [self paymentResultCallback:resultDict payType:PayTypeWX];
    }];
    
    if (errmsg.length > 0) {
        
        NSError *payError = [NSError errorWithDomain:[AppManager sharedManager].baseURLStr code:-1 userInfo:@{@"errmsg":errmsg}];
        
        if (self.resultBlock) {
            self.resultBlock(nil, payError);
        }
    }
    
    
}

#pragma mark -支付宝 微信 结果回调
- (void)paymentResultCallback:(id)resultObj payType:(PayType)type {
    
    switch (type) {
        case PayTypeAlipay: {
            
            NSInteger resultCode = [resultObj[@"resultStatus"] integerValue];
            NSString *result = @"";
            
            if (resultCode == 9000) {
                
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[resultObj[@"result"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

                [self verifyOrderWithOrderID:dict[@"alipay_trade_app_pay_response"][@"out_trade_no"] notorderID:resultObj[@"result"] payType:type currency:nil];
                
                return;
            } else if (resultCode == 6001) {
                
                result = MYLocalizedString(@"PUBLIC_CANCEL", nil);
            } else if (resultCode == 4000) {
                result = MYLocalizedString(@"PAYORDER_FAILED_TITLE", nil);
            } else {
                result = resultObj[@"memo"];
            }
            
            NSError *payError = [NSError errorWithDomain:[AppManager sharedManager].baseURLStr code:resultCode userInfo:@{@"errmsg":result}];
            
            
            if (resultCode != 9000 && self.resultBlock) {
                self.resultBlock(nil, payError);
            }
            
        }
            break;
            
        case PayTypeWX: {
            
            NSInteger code = [resultObj[@"errCode"] integerValue];
            
            NSString *result = [NSString stringWithFormat:@"errcode:%d", (int)code];
            if(code == 0){//支付成功
                [self verifyOrderWithOrderID:self.orderid notorderID:nil payType:type currency:nil];
                return;
            } else if (code == -1) {
                
                result = MYLocalizedString(@"PAYORDER_FAILED_TITLE", nil);
            } else if (code == -2) {
                
                result = MYLocalizedString(@"PUBLIC_CANCEL", nil);
            } else {
                
                result = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", (int)code,resultObj[@"errStr"]];
            }
            
            NSError *payError = [NSError errorWithDomain:[AppManager sharedManager].baseURLStr code:code userInfo:@{@"errmsg":result}];
            
            if (self.resultBlock) {
                self.resultBlock(nil, payError);
            }
        }
            break;
            
        default:
            break;
    }
}

//
//// -----------------------------------------------------------------------------------------------------------
//// --------------------------------------PayPal---------------------------------------------------------------
//// -----------------------------------------------------------------------------------------------------------
//
//- (PayPalConfiguration *)payPalConfig {
//
//    if (!_payPalConfig) {
//
//        _payPalConfig = [[PayPalConfiguration alloc] init];
//        //是否接受信用卡
//        _payPalConfig.acceptCreditCards = NO;
//
//        //商家名称
//        _payPalConfig.merchantName = @"Audio Ctrip Network Co., Ltd.";
//
//        //商家隐私协议网址和用户授权网址-说实话这个没用到
//        _payPalConfig.merchantPrivacyPolicyURL = [NSURL URLWithString:@"https://www.paypal.com/webapps/mpp/ua/privacy-full"];
//        _payPalConfig.merchantUserAgreementURL = [NSURL URLWithString:@"https://www.paypal.com/webapps/mpp/ua/useragreement-full"];
//
//        //paypal账号下的地址信息
//        _payPalConfig.payPalShippingAddressOption = PayPalShippingAddressOptionNone;
//
//        //配置语言环境
//        _payPalConfig.languageOrLocale = [NSLocale preferredLanguages][0];
//    }
//
//    return _payPalConfig;
//}
//
//#pragma mark -PayPal支付请求
//- (void)payPayPalWithOrderObj:(NSDictionary *)result vc:(UIViewController *)vc {
//
//
////#ifdef IG_AppStore
////    [PayPalMobile preconnectWithEnvironment:PayPalEnvironmentProduction];
////#else
////    [PayPalMobile preconnectWithEnvironment:PayPalEnvironmentSandbox];
////#endif
//
//    [PayPalMobile preconnectWithEnvironment:PayPalEnvironmentProduction];
//    PayPalPayment *payment = [[PayPalPayment alloc] init];
//
//    //订单总额
//    payment.amount = [NSDecimalNumber decimalNumberWithString:[result[@"amount"] stringValue]];
//
//    payment.shortDescription = result[@"subject"];
//    //货币类型-RMB是没用的
//    payment.currencyCode = result[@"currency"];
//    payment.custom = result[@"custom"];
//
//    PayPalPaymentViewController *paypalVC = [[PayPalPaymentViewController alloc] initWithPayment:payment configuration:self.payPalConfig delegate:self];
//
//    //模态展示
//    [vc presentViewController:paypalVC animated:YES completion:nil];
//}
//#pragma mark -PayPal支付回调
//- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
//
//    NSLog(@"PayPal Payment Success! %@",completedPayment.confirmation);
//    // 支付成功 去服务器验证
//    //
//    NSString *orderid = completedPayment.confirmation[@"response"][@"id"];
//
//    [self verifyOrderWithOrderID:orderid notorderID:nil payType:PayTypePaypal currency:nil];
//    [paymentViewController dismissViewControllerAnimated:YES completion:nil];
//}
//
////用户取消支付回调此方法
//- (void)payPalPaymentDidCancel:(PayPalPaymentViewController *)paymentViewController {
//
//
//    NSError *payError = [NSError errorWithDomain:[AppManager sharedManager].baseURLStr code:-1 userInfo:@{@"errmsg":MYLocalizedString(@"PUBLIC_CANCEL", nil)}];
//
//    if (self.resultBlock) {
//        self.resultBlock(nil, payError);
//    }
//
//    [paymentViewController dismissViewControllerAnimated:YES completion:nil];
//}
//
//// -----------------------------------------------------------------------------------------------------------
//// --------------------------------------苹果支付---------------------------------------------------------------
//// -----------------------------------------------------------------------------------------------------------
//
//#pragma mark -苹果支付 请求
//- (void)payApplePayObj:(NSDictionary *)result vc:(UIViewController *)vc {
//
//    if([PKPaymentAuthorizationViewController canMakePayments]) {
//
//        PKPaymentRequest *request = [[PKPaymentRequest alloc] init];
//
//        PKPaymentSummaryItem *widget1 = [PKPaymentSummaryItem summaryItemWithLabel:@"Widget 1"
//                                                                            amount:[NSDecimalNumber decimalNumberWithString:@"0.99"]];
//
//        PKPaymentSummaryItem *widget2 = [PKPaymentSummaryItem summaryItemWithLabel:@"Widget 2"
//                                                                            amount:[NSDecimalNumber decimalNumberWithString:@"1.00"]];
//
//        PKPaymentSummaryItem *total = [PKPaymentSummaryItem summaryItemWithLabel:@"Grand Total"
//                                                                          amount:[NSDecimalNumber decimalNumberWithString:@"1.99"]];
//
//        request.paymentSummaryItems = @[widget1, widget2, total];
//        request.countryCode = @"US";
//        request.currencyCode = @"USD";
//        request.supportedNetworks = @[PKPaymentNetworkAmex, PKPaymentNetworkMasterCard, PKPaymentNetworkVisa];
//        request.merchantIdentifier = @"merchant.com.demo.crittercismdemo";
//        request.merchantCapabilities = PKMerchantCapabilityEMV;
//
//        PKPaymentAuthorizationViewController *paymentPane = [[PKPaymentAuthorizationViewController alloc] initWithPaymentRequest:request];
//        paymentPane.delegate = self;
//        [vc presentViewController:paymentPane animated:TRUE completion:nil];
//
//    } else {
//        [IGUtil showToast:@"此设备不可使用苹果支付"];
//    }
//}
//
//#pragma mark -苹果支付 回调
//- (void)paymentAuthorizationViewController:(PKPaymentAuthorizationViewController *)controller
//                       didAuthorizePayment:(PKPayment *)payment
//                                completion:(void (^)(PKPaymentAuthorizationStatus status))completion {
//
//    NSLog(@"Payment was authorized: %@", payment);
//
//    // do an async call to the server to complete the payment.
//    // See PKPayment class reference for object parameters that can be passed
//    BOOL asyncSuccessful = FALSE;
//
//    // When the async call is done, send the callback.
//    // Available cases are:
//    //    PKPaymentAuthorizationStatusSuccess, // Merchant auth'd (or expects to auth) the transaction successfully.
//    //    PKPaymentAuthorizationStatusFailure, // Merchant failed to auth the transaction.
//    //
//    //    PKPaymentAuthorizationStatusInvalidBillingPostalAddress,  // Merchant refuses service to this billing address.
//    //    PKPaymentAuthorizationStatusInvalidShippingPostalAddress, // Merchant refuses service to this shipping address.
//    //    PKPaymentAuthorizationStatusInvalidShippingContact        // Supplied contact information is insufficient.
//
//    if(asyncSuccessful) {
//        completion(PKPaymentAuthorizationStatusSuccess);
//
//        // do something to let the user know the status
//
//        NSLog(@"Payment was successful");
//
//        //        [Crittercism endTransaction:@"checkout"];
//
//    } else {
//        completion(PKPaymentAuthorizationStatusFailure);
//
//        // do something to let the user know the status
//
//        NSLog(@"Payment was unsuccessful");
//
//        //        [Crittercism failTransaction:@"checkout"];
//    }
//
//}
//
//- (void)paymentAuthorizationViewControllerDidFinish:(PKPaymentAuthorizationViewController *)controller {
//
//
//
//}

@end

